<template>
  <div>
    <el-form
      :model="userForm"
      :rules="rules"
      ref="userForm"
    >
      <el-form-item prop="password">
        <el-input
          type="password"
          placeholder="请输入新密码"
          v-model="userForm.password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item prop="email">
        <el-input
          v-model="userForm.email"
          placeholder="请输入邮箱"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="smscode">
        <div class="g-inline">
          <el-input
            placeholder="请输入验证码"
            v-model="userForm.smscode"
          >
          </el-input>
          <el-button
            type="primary"
            style="margin-left: 5px;"
            :disabled="smscode.disabled||codeLoading"
            @click="submitSmsForm('userForm')"
          >{{smscode.tip}}</el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          class="g-form"
          type="primary"
          :loading="loading"
          @click="submitForm('userForm')"
        >重置密码</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { setToken } from '@/utils/auth'
import { EMailRegex } from '@/utils/regex'
import { mailCodeVerify, emailResetPassword } from '@/api/auth'
export default {
  name: 'ResetForm',
  data () {
    return {
      loading: false,
      codeLoading: false,
      smscode: {
        tip: '发送验证码',
        time: 60,
        timer: null,
        disabled: false
      },
      userForm: {
        password: '',
        email: '',
        smscode: ''
      },
      rules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!EMailRegex.test(value)) {
                callback(new Error('邮箱格式不正确！'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        password: [
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请输入密码'))
              } else {
                if (this.userForm.repassword !== '') {
                  this.$refs.userForm.validateField('repassword')
                }
                callback()
              }
            },
            trigger: 'blur'
          },
          { min: 4, max: 20, message: '密码长度在4-20之间', trigger: 'blur' }
        ],
        repassword: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请再次输入密码'))
              } else if (value !== this.userForm.password) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        smscode: [
          { required: true, message: '请输入短信验证码', trigger: 'blur' },
          { min: 4, max: 4, message: '长度为4个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 提交邮箱表单
    submitSmsForm (formName) {
      this.$refs[formName].validateField('email', errMsg => {
        if (errMsg) {
        } else {
          this.handleMailCodeVerify()
        }
      })
    },
    // 发送验证码
    async handleMailCodeVerify () {
      this.codeLoading = true
      await mailCodeVerify(this.userForm.email)
      this.codeLoading = false
      this.$notify({
        message: '验证码已发送，请查看邮箱',
        duration: 0
      })
      this.smscode.tip = this.smscode.time + '秒后重试'
      this.smscode.disabled = true
      this.smscode.timer = setInterval(() => {
        this.smscode.time--
        if (this.smscode.time > 0) {
          this.smscode.tip = this.smscode.time + '秒后重试'
        } else {
          clearInterval(this.smscode.timer)
          this.smscode.disabled = false
          this.smscode.time = 60
          this.smscode.tip = '重新发送'
        }
      }, 1000)
    },
    // 提交重置密码表单
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleResetPassword()
        } else {
          return false
        }
      })
    },
    // 重置密码
    async handleResetPassword () {
      this.loading = true
      const {
        data: { token, refreshToken }
      } = await emailResetPassword(
        this.userForm.password,
        this.userForm.email,
        this.userForm.smscode
      )
      this.loading = false
      this.$message.success('密码重置成功，自动登录')
      setToken('token', token)
      setToken('refreshToken', refreshToken)
      this.$router.push({ path: '/' })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
